//
//  BindingViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/30.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "BindingViewController.h"
#import "LCChatKitExample.h"

@interface BindingViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *accountTF; //用户名


@end

@implementation BindingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"账号绑定";
    
    [self setupUI];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.accountTF resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.accountTF resignFirstResponder];
}

- (void)setupUI {
    MJWeakSelf;
    [self.tableView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        
        [weakSelf.accountTF resignFirstResponder];
    }]];
    
    self.tableView.separatorStyle = NO;
    
    self.tableView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.96 alpha:1.00];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kMainWidth, 150)];
    
    headerView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.tableHeaderView = headerView;
    
    CGFloat y = AUTO_MATE_HEIGHT(kSpaceX);
    
    _accountTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:@"请输入要绑定子账号用户名" leftLabelText:@"子账号"];
    _accountTF.keyboardType = UIKeyboardTypeDefault;
    
    [headerView addSubview:_accountTF];
    
    [_accountTF addLineViewPositionType:kBottom_Type];
    
    //绑定
    
    y = _accountTF.maxY_pro + 20;
    
    UIButton *bindingBtn = [[UIButton alloc] initWithFrame:CGRectMake(kSpaceX, y, kMainWidth - kSpaceX*2, 35)];
    
    bindingBtn.backgroundColor = [UIColor colorWithRed:0.06 green:0.47 blue:0.91 alpha:1.00];
    
    [bindingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [headerView addSubview:bindingBtn];
    
    if (_pName.length > 0 && _cName.length == 0) {
        //有父账号绑定了自己
//        _accountTF.text = _pName;
//        
//        _accountTF.userInteractionEnabled = NO;
//        bindingBtn.userInteractionEnabled = NO;
        
        [bindingBtn setTitle:@"绑定" forState:UIControlStateNormal];
        
        [bindingBtn addTarget:self action:@selector(bingdingAction) forControlEvents:UIControlEventTouchUpInside];
        
    } else if (_cName.length > 0 && _pName.length == 0) {
        //自己绑定了子账号端
        _accountTF.userInteractionEnabled = NO;
        
        _accountTF.text = _cName;
        
        [bindingBtn setTitle:@"解除绑定" forState:UIControlStateNormal];
        
        [bindingBtn addTarget:self action:@selector(removeBingdingAction) forControlEvents:UIControlEventTouchUpInside];
        
        
    }else if (_pName.length > 0 && _cName.length > 0) {
        _accountTF.userInteractionEnabled = NO;
        
        _accountTF.text = _cName;
        
        [bindingBtn setTitle:@"解除绑定" forState:UIControlStateNormal];
        
        [bindingBtn addTarget:self action:@selector(removeBingdingAction) forControlEvents:UIControlEventTouchUpInside];
        
    } else {
        
        [bindingBtn setTitle:@"绑定" forState:UIControlStateNormal];
        
        [bindingBtn addTarget:self action:@selector(bingdingAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
}

#pragma mark - 绑定
- (void)bingdingAction {
    
    [LCCKUtil showProgress];
    
    AVUser *currentUser = [AVUser currentUser];
    
    if (_accountTF.text.length == 0) {
        
        [LCCKUtil showNotificationWithTitle:@"请输入子账号的用户名" subtitle:nil type:LCCKMessageNotificationTypeError];
        
        [LCCKUtil hideProgress];
        
        return;
    }else if ([_accountTF.text isEqualToString:currentUser.username]) {
        
        
        [LCCKUtil showNotificationWithTitle:@"该用户名为本人" subtitle:nil type:LCCKMessageNotificationTypeError];
        
        [LCCKUtil hideProgress];
        
        return;
        
    }else if (_pName.length > 0 && [_pName isEqualToString:_accountTF.text]) {
        
        [LCCKUtil showNotificationWithTitle:@"该用户为您的父账号" subtitle:nil type:LCCKMessageNotificationTypeError];
        
        [LCCKUtil hideProgress];
        
        return;
        
    } else {
        
//        __block NSString *childObjectId = @"";
        
        __block AVUser *childUser = nil;
        
        MJWeakSelf;
        
        
        void(^bindingChildblock)() = ^(){
            
            //子账号不存在的情况下
            AVObject *cUser = [AVObject objectWithClassName:kRelationship];
            
            [cUser setObject:weakSelf.accountTF.text forKey:kUsername];
            
            [cUser setObject:currentUser forKey:kParent];
            
            [cUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                    if (weakSelf.bindingBlock) {
                        weakSelf.bindingBlock(weakSelf.accountTF.text);
                        
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                        
                        [LCCKUtil showNotificationWithTitle:@"绑定成功" subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                        
                        //指定推送给添加的用户
                        AVPush *push = [[AVPush alloc] init];
                        [push setChannel: weakSelf.accountTF.text];
                        [push setMessage:NSStringFormat(@"%@ 绑定您为子账号了",weakSelf.accountTF.text)];
                        [push sendPushInBackground];
                    }
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
            }];
        };
        
        
        //子账号存在的情况下去更新
        void(^updateChildren)(NSString *) = ^(NSString *objectId){
            
            AVObject *obj = [AVObject objectWithClassName:kRelationship objectId:objectId];
            
            [obj setObject:currentUser forKey:kParent];
            
            [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    if (weakSelf.bindingBlock) {
                        weakSelf.bindingBlock(weakSelf.accountTF.text);
                        
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                        
                        [LCCKUtil showNotificationWithTitle:@"绑定成功" subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                        
                        //指定推送给添加的用户
                        
                        AVPush *push = [[AVPush alloc] init];
                        [push setChannel:weakSelf.accountTF.text];
                        [push setMessage:NSStringFormat(@"%@ 绑定您为子账号了",[AVUser currentUser].username)];
                        [push sendPushInBackground];
                    }
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
            }];
        };
        
        
        //查找子账号是否在关系表中
        void(^queryChildBlock)() = ^(){
            
            AVQuery *query = [AVQuery queryWithClassName:kRelationship];
            
            [query whereKey:kUsername equalTo:_accountTF.text];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                
                if (!error) {
                    
                    if (objects.count > 0) {
                        
                        if (![objects[0] objectForKey:kParent]) {
                            //该账号没有绑定父账号，可以绑定
                            updateChildren([objects[0] objectForKey:kobjectId]);
                        }
                    } else {
                        //没有查到--，可以绑定
                        bindingChildblock();
                    }
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
            }];
        };
        
        //没有该条数据的情况下
        void(^bindingParentBlock)() = ^(){
            
            AVObject *pObject = [AVObject objectWithClassName:kRelationship];
            
            [pObject setObject:currentUser.username forKey:kUsername];
            
            [pObject setObject:childUser forKey:kChildren];
            
            [pObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    queryChildBlock();
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
            }];
            
        };
        
        //父账号存在情况下去更新
        void(^updateParent)(NSString *) = ^(NSString *objectId){
            
            AVObject *obj = [AVObject objectWithClassName:kRelationship objectId:objectId];
            
            [obj setObject:childUser forKey:kChildren];
            
            [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
               
                if (succeeded) {
                    queryChildBlock();
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
            }];
            
        };
        
        //查找自己是否在关系表中
        void(^queryParentRelationship)() = ^(){
            
            AVQuery *query = [AVQuery queryWithClassName:kRelationship];
            
            [query whereKey:kUsername equalTo:currentUser.username];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                
                if (!error) {
                    
                    if (objects.count > 0) {
                        
                        if (![objects[0] objectForKey:kChildren]) {
                            //该账号没有绑定父账号，可以绑定
                            updateParent([objects[0] objectForKey:kobjectId]);
                        }
                    } else {
                        //没有查到--，可以绑定
                        bindingParentBlock();
                    }
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
            }];
            
        };
        
        //查找是否存在该用户
        void(^queryUser)() = ^(){
          
            AVQuery *query = [AVQuery queryWithClassName:kUser];
            
            [query whereKey:kUsername equalTo:_accountTF.text];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                
                if (!error) {
                    
                    if (objects.count > 0) {
                        childUser = ((AVUser *)objects[0]);
                        queryParentRelationship();
                        
                    } else {
                        [LCCKUtil hideProgress];
                        [LCCKUtil showNotificationWithTitle:@"该用户不存在" subtitle:nil type:LCCKMessageNotificationTypeError];
                    }
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
            }];
            
        };
        
        queryUser();
        
    }
    
}

#pragma mark - 解除绑定
- (void)removeBingdingAction {
    
    [LCCKUtil showProgress];
    
    AVUser *currentUser = [AVUser currentUser];
    
    MJWeakSelf;
    void(^removeChildBingding)() = ^() {
        AVQuery *cQuery = [AVQuery queryWithClassName:kRelationship];
        
        [cQuery whereKey:kUsername equalTo:_accountTF.text];
        
        [cQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            
            if (!error) {
                
                if (objects.count > 0) {
                    
                    AVObject *obj = [AVObject objectWithClassName:kRelationship objectId:[objects[0] objectForKey:kobjectId]];
                    [obj setObject:nil forKey:kParent];
                    
                    [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                        if (succeeded) {
                            
                            if (weakSelf.removeBindingBlock) {
                                weakSelf.removeBindingBlock();
                                
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                                
                                [LCCKUtil showNotificationWithTitle:@"解绑成功" subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                                
                                //指定推送给添加的用户
                                AVPush *push = [[AVPush alloc] init];
                                [push setChannel: weakSelf.accountTF.text];
                                [push setMessage:NSStringFormat(@"%@ 解绑您的账号了",weakSelf.accountTF.text)];
                                [push sendPushInBackground];
                            }
                            
                        } else {
                            [LCCKUtil hideProgress];
                            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                        }
                    }];
                }
                
            } else {
                [LCCKUtil showProgress];
                [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
            }
        }];
    };
    
    AVQuery *pQuery = [AVQuery queryWithClassName:kRelationship];
    
    [pQuery whereKey:kUsername equalTo:currentUser.username];
    
    [pQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (!error) {
            
            if (objects.count > 0) {
                
                AVObject *obj = [AVObject objectWithClassName:kRelationship objectId:[objects[0] objectForKey:kobjectId]];
                [obj setObject:nil forKey:kChildren];
                
                [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    if (succeeded) {
                        removeChildBingding();
                    } else {
                        removeChildBingding();
                    }
                }];
            }
            
            
        } else {
            [LCCKUtil hideProgress];
            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
        }
    }];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
 
 // Configure the cell...
 
 return cell;
 }
 */

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
